package br.com.ca5.entity;

import java.lang.reflect.Field;

import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;

import org.apache.myfaces.custom.navmenu.NavigationMenuItem;
import org.springframework.beans.factory.annotation.Autowired;

import br.com.ca5.mbean.LoginMBean;
import br.com.ca5.service.MenuService;

public class MBeanBase {

	public NavigationMenuItem[] navItems;

	public MenuService menuService;

	public Usuario usuarioLogado;
	
	public boolean pesquisa;
	public boolean novo;
	public boolean edicao;
	
	@PostConstruct
	public void onCreate() {
		LoginMBean loginMBean = (LoginMBean) FacesContext.getCurrentInstance()
				.getApplication().evaluateExpressionGet(
						FacesContext.getCurrentInstance(), "#{loginMBean}",
						LoginMBean.class);
		usuarioLogado = loginMBean.getUsuario();
		navItems = menuService.buscarMenuPorUsuario(usuarioLogado);

		pesquisa = true;
		novo = false;
		edicao = false;
		
		onCreateMBean();
		
	}
	
	public void anulaCamposVazios(Object ob){
		for(Field f: ob.getClass().getDeclaredFields()){
			try {
				if(f.getType().equals(String.class)){
					f.setAccessible(true);
					String value = (String) f.get(ob);
					if("".equals(value)){
						f.set(ob, null);
					}
				}
				
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public void criar(){
		novo = true;
		pesquisa = false;
		edicao = false;
	}
	
	public void editar(){
		edicao = true;
		pesquisa = false;
		novo = false;
	}
	
	public void find(){
		pesquisa = true;
		edicao = false;
		novo = false;
	}

	public void onCreateMBean() {
	}

	public NavigationMenuItem[] getNavItems() {
		return navItems;
	}

	public void setNavItems(NavigationMenuItem[] navItems) {
		this.navItems = navItems;
	}

	public MenuService getMenuService() {
		return menuService;
	}

	@Autowired
	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	public Usuario getUsuarioLogado() {
		return usuarioLogado;
	}

	public void setUsuarioLogado(Usuario usuarioLogado) {
		this.usuarioLogado = usuarioLogado;
	}

	public boolean getPesquisa() {
		return pesquisa;
	}

	public void setPesquisa(boolean pesquisa) {
		this.pesquisa = pesquisa;
	}

	public boolean getNovo() {
		return novo;
	}

	public void setNovo(boolean novo) {
		this.novo = novo;
	}

	public boolean getEdicao() {
		return edicao;
	}

	public void setEdicao(boolean edicao) {
		this.edicao = edicao;
	}
}
